import { ShopState, ShopItem } from '../../interface/index.d';

const initState: ShopState = {
    list: []
};

export const cartReducer = (state = initState, action: any) => {
    const newState: ShopState = JSON.parse(JSON.stringify(state));

    switch (action.type) {
        case 'ADD_TO_CART':
            if (action.item.checked) {
                if (newState.list.length === 0) {
                    newState.list = [...newState.list, action.item];
                    return newState;
                }

                newState.list.map((item) => {
                    if (item.id !== action.item.id) {
                        newState.list = [...newState.list, action.item];
                    } else {
                        item.quantity += action.item.quantity;
                    }
                });
                return newState;
            }

            return newState;
        default:
            return state;
    }
}